package edu.kit.csl.cratylus.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import edu.kit.csl.cratylus.datatypes.Vocabulary;
import edu.kit.csl.cratylus.datatypes.Word;
import edu.kit.csl.cratylus.extraction.WritingSystem;

/**
 * This utility class mainly provides the method 
 * {@link #dumpToFileSystem(Vocabulary, WritingSystem, String)} for writing
 * the vocabulary to the file system in form of a pronunciation dictionary.
 * The file is in Janus format.
 */
final public class VocabularyDumper {
	
	/**
	 * Writes the vocabulary to the file system in Janus pronunciation
	 * dictionary format.
	 * 
	 * @param voc vocabulary to dump
	 * @param ws the writing system which should be used
	 * @param fileName the path to the file
	 * @throws IOException if the file could not be written
	 * @throws NullPointerException if one of the parameters is null
	 */
	static public void dumpToFileSystem(Vocabulary voc, WritingSystem ws,
			String fileName) throws IOException {
		FileWriter fs = new FileWriter(fileName);
		BufferedWriter out = new BufferedWriter(fs);
		for (Word word : voc) {
			out.write(ws.convert(word) + " "
					+ generatePronunciation(word.getContent()) + "\n");
		}
		out.close();
	}
	
	/*
	 * Generate a string formed like '{{h WB} a l {o WB}}' in order to use it
	 * as pronunciation dictionary entry. 
	 */
	static private String generatePronunciation(String str) {
		String[] phonemes = str.trim().split(" ");
		final int n = phonemes.length;
		if (n == 0) {
			return "{{SIL WB}}";
		}
		phonemes[0] = "{" + phonemes[0] + " WB}";
		if (n > 1) {
			phonemes[n - 1] = "{" + phonemes[n - 1] + " WB}";
		}
		StringBuilder s = new StringBuilder();
		for (String phoneme : phonemes) {
			s.append(" " + phoneme);
		}
		return "{" + s.toString().trim()+ "}";
	}
}
